﻿using System.Collections.ObjectModel;
using CodeIn.Ui.Dock;
using CodeIn.Ui.StatusBar;
using Mvvm;
using System.Windows.Threading;
using System;
using System.Windows.Data;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections.Specialized;
using CodeIn.Diagnostics;

namespace CodeIn.Ui {
	public class MainWindowViewModel : BaseViewModel {
		public bool IsInitializing { get; set; }
		public ObservableCollection<PanelViewModel> MiddleTabItems { get; private set; }
		public ObservableCollection<PanelViewModel> BottomTabItems { get; private set; }
		public ObservableCollection<PanelViewModel> TopLeftTabItems { get; private set; }
		public ObservableCollection<PanelViewModel> BottomLeftTabItems { get; private set; }
		public StatusBarViewModel StatusBarViewModel { get; private set; }

		public MainWindowViewModel() {
			IsInitializing = true;

			MiddleTabItems = new ObservableCollection<PanelViewModel>();
			BottomTabItems = new ObservableCollection<PanelViewModel>();
			TopLeftTabItems = new ObservableCollection<PanelViewModel>();
			BottomLeftTabItems = new ObservableCollection<PanelViewModel>();

			MiddleTabItems.CollectionChanged += OnDockCollectionChanged;
			BottomTabItems.CollectionChanged += OnDockCollectionChanged;
			TopLeftTabItems.CollectionChanged += OnDockCollectionChanged;
			BottomLeftTabItems.CollectionChanged += OnDockCollectionChanged;

			StatusBarViewModel = new StatusBarViewModel();

			UiHelper.PanelRequested += (s, e) => {
				UiHelper.Synchronize(() => {
					switch (e.Side) {
						case PanelSide.MIDDLE: MiddleTabItems.Add(e.PanelViewModel); break;
						case PanelSide.BOTTOM: BottomTabItems.Add(e.PanelViewModel); break;
						case PanelSide.TOPLEFT: TopLeftTabItems.Add(e.PanelViewModel); break;
						case PanelSide.BOTTOMLEFT: BottomLeftTabItems.Add(e.PanelViewModel); break;
					}
				});
			};
		}

		private void OnDockCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
			if (e.NewItems != null && e.NewItems.Count != 0) {
				foreach (PanelViewModel panel in e.NewItems)
					panel.CloseRequested += OnPanelCloseRequested;
				var collection = sender as ObservableCollection<PanelViewModel>;
				var view = CollectionViewSource.GetDefaultView(sender);
				if (!IsInitializing)
					UiHelper.Synchronize(() => { view.MoveCurrentToLast(); });
			}

			if (e.OldItems != null && e.OldItems.Count != 0)
				foreach (PanelViewModel panel in e.OldItems)
					panel.CloseRequested -= OnPanelCloseRequested;
		}

		private void OnPanelCloseRequested(object sender, PanelViewModel.CloseRequestedEventArgs e) {
			if (e.Handled)
				return;

			var panel = sender as PanelViewModel;
			Debug.Assert(panel != null, "panel is null");
			MiddleTabItems.Remove(panel);
			BottomTabItems.Remove(panel);
			TopLeftTabItems.Remove(panel);
			BottomLeftTabItems.Remove(panel);
		}
	}
}
